package edu.nf.meituan.dao.order.user.impl;

import edu.nf.meituan.dao.order.user.UserOrderDAO;
import edu.nf.meituan.model.order.Order;
import edu.nf.meituan.model.order.OrderItem;
import edu.nf.meituan.model.order.user.UserOrder;
import edu.nf.meituan.model.order.user.UserOrdersItem;
import edu.nf.util.DBUtils;
import org.nf.db.util.SqlExecutor;
import org.nf.db.util.result.BeanListHandler;
import java.util.List;

/**
 * @Date 2023/6/19
 * @Author zgm
 */
public class UserOrderDAOImpl implements UserOrderDAO {
    @Override
    public List<UserOrder> queryUserOrder(int id) {
        SqlExecutor executor = new SqlExecutor(DBUtils.getConnection());
        String sql = "SELECT order_id , rider_id , orders_status , shop_img , shop_name,orders_created_at FROM orders INNER JOIN shop ON orders.shop_id = shop.shop_id WHERE u_id = ? AND orders_type = 'user'";
        return executor.executeQuery(sql, new BeanListHandler<>(UserOrder.class),id);
    }

    @Override
    public int updateOrderStatus(int orderId, int status) {
        SqlExecutor executor = new SqlExecutor(DBUtils.getConnection());
        String sql = "UPDATE orders SET orders_status = ? WHERE order_id = ?";
        return executor.executeUpdate(sql,orderId,status);
    }

    @Override
    public List<UserOrdersItem> queryUserOrdersItem(int orderId) {
        SqlExecutor executor = new SqlExecutor(DBUtils.getConnection());
        String sql = "SELECT orders.order_id,orders_type,items_picture , orders.total_price, orders_item.items_id, orders_item.quantity, items.items_name, items.items_price "+
                " FROM orders INNER JOIN orders_item ON orders.order_id = orders_item.order_id "+
                " INNER JOIN items ON orders_item.items_id = items.items_id "+
                " WHERE orders.order_id = ?";
        return executor.executeQuery(sql, new BeanListHandler<>(UserOrdersItem.class),orderId);
    }

    @Override
    public int addOrder(Order order) {
        SqlExecutor executor = new SqlExecutor(DBUtils.getConnection());
        String sql = "insert into orders(u_id,shop_id,total_price,orders_type,orders_details) VALUES(?,?,?,'user',?);";
        // 保存订单信息并返回自增的主键
        return(int) executor.insert(sql, order.getUid(),
                order.getShopId(),
                order.getTotalPrice(),
                order.getOrdersDetails());
    }

    @Override
    public int addOrderItem(OrderItem orderItem) {
        SqlExecutor executor = new SqlExecutor(DBUtils.getConnection());
        String sql = "INSERT INTO orders_item(order_id,items_id,quantity) VALUES(?,?,?)";
        return executor.executeUpdate(sql,orderItem.getOrderId(),
                orderItem.getItemsId(),
                orderItem.getQuantity());
    }
}
